package com.um.psystem.service.mtService.impl;

import cn.hutool.core.util.StrUtil;
import com.um.psystem.entity.ExcelHeader;
import com.um.psystem.mapper.platform.PublicMapper;
import com.um.psystem.model.vo.JsonResult;
import com.um.psystem.service.mtService.IAssetsDeliveryService;
import com.um.psystem.utils.EasyExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Auther: qy
 * @Date: 2020/9/27 - 20:32
 * @Description: com.um.psystem.service.mtService.impl
 * @version: 1.0
 */
@Service
public class AssetsDeliveryService implements IAssetsDeliveryService {

    @Autowired
    PublicMapper publicMapper;

    @Override
    public List<Map<String, Object>> getDeliveryList(Map map) {
        String k3_code="";
        String sqltmp="";
        String delivery_man="";
        String type_dtl_no="";
        String id="";
        Map paramsMap = new HashMap();
        Integer page = Integer.parseInt((map.get("page")!=null?map.get("page").toString():"0"));
        Integer rows = Integer.parseInt((map.get("rows")!=null?map.get("rows").toString():"0"));

        if(StrUtil.isNotBlank(map.get("id")!=null?map.get("id").toString():null)){
            sqltmp+=" and a.id=#{id}";
            id =map.get("id").toString();
            paramsMap.put("id",id);
        }
        if(StrUtil.isNotBlank(map.get("type_dtl_no")!=null?map.get("type_dtl_no").toString():null)){
            sqltmp+=" and b.type_dtl_no=#{type_dtl_no}";
            type_dtl_no =map.get("type_dtl_no").toString();
            paramsMap.put("type_dtl_no",type_dtl_no);
        }
        if(StrUtil.isNotBlank(map.get("k3_code")!=null?map.get("k3_code").toString():null)){
            sqltmp+=" and b.k3_code=#{k3_code}";
            k3_code =map.get("k3_code").toString();
            paramsMap.put("k3_code",k3_code);
        }
        if(StrUtil.isNotBlank(map.get("delivery_man")!=null?map.get("delivery_man").toString():null)){
            sqltmp+=" and a.delivery_man=#{delivery_man}";
            delivery_man =map.get("delivery_man").toString();
            paramsMap.put("delivery_man",delivery_man);
        }
        String  sql = " select count(*) as totals from ws_eng_assets_delivery_record a " +
                " join ws_eng_assets_type_dtl b on a.assets_id=b.type_dtl_id" +
                " where 1=1 "+sqltmp;
        System.out.println("--------------------------------------");
        System.out.println("sql1:"+sql);
        paramsMap.put("sqlStr",sql);
        int totals=0;
        List<Map<String,Object>> list_count = publicMapper.getPublicItems(paramsMap);
        if(list_count.size()>0){
            totals = Integer.parseInt(list_count.get(0).get("totals").toString());
        }
        sql = " select a.*,c.conDept,c.conProductNum,"+totals+ " as totals,b.type_main_name,b.type_dtl_name as mt_name,b.type_dtl_no as mt_code,b.k3_code,b.model,b.sizes,b.unit from " +
                " ws_eng_assets_delivery_record a join ws_eng_assets_type_dtl b on a.assets_id=b.type_dtl_id " +
                " LEFT JOIN uws_produceorder_confirmation_query c on a.erp<>'' AND a.erp=c.conErpNo " +
                " where 1=1 "+sqltmp+" order by id desc";
        if(page!=0 && rows!=0){
            sql+= " limit #{startIndex},#{rows} ";
            paramsMap.put("startIndex",(page-1)*rows);
            paramsMap.put("rows",rows);
        }
        paramsMap.put("sqlStr",sql);
        System.out.println("--------------------------------------");
        System.out.println("sql2:"+sql);
        return publicMapper.getPublicItems(paramsMap);
    }

    @Override
    public List<Map<String, Object>> getMtInfo(Map map) {
        return null;
    }

    @Override
    public List<Map<String, Object>> getDeliveryInfo(Map map) {
        Map paramsMap = new HashMap();
        String id = (String) map.get("id");
        String sql = "select a.id,a.delivery_num as num,a.remarks,a.erp,a.purpose,a.quantity_ret,a.delivery_man,b.k3_code as k3Code,b.type_dtl_no as typeDtlNo," +
                "b.type_main_name as typeMain,b.type_dtl_name as mtName,b.model,b.sizes,b.unit " +
                "from ws_eng_assets_delivery_record a join ws_eng_assets_type_dtl b " +
                "on a.assets_id = b.type_dtl_id " +
                "where a.id ="+id;
        paramsMap.put("sqlStr",sql);
        return publicMapper.getPublicItems(paramsMap);
    }

    @Override
    public JsonResult<Integer> updateMtDeliveryRecord(Map map) {
        //----------这一步验证是否被锁定-----------//
        Map pmap = new HashMap();
        pmap.put("id",map.get("id").toString());
        List<Map<String,Object>> list = getDeliveryList(pmap);
        if (list.size()>0)
        {
            if(!list.get(0).get("state").toString().equals("0"))
            { return JsonResult.error(408,"修改失败可能是记录已锁定"); }
        }
        else
        {return JsonResult.error(400,"修改失败，未找到对应记录"); }
        //----------这一步验证是否被锁定-----------//

        Map paramsMap = new HashMap();
        //找到对应的assets_id
        String assets_id = "";
        String newId = "";
        String sql = "select * from ws_eng_assets_type_dtl where type_dtl_no = #{type_dtl_no}";
        paramsMap.put("type_dtl_no",map.get("typeDtlNo"));
        paramsMap.put("sqlStr",sql);
        List<Map<String,Object>> list_type_dtl = publicMapper.getPublicItems(paramsMap);
        if(list_type_dtl.size()>0){
            assets_id = list_type_dtl.get(0).get("type_dtl_id").toString();
        }
        //先要判断是否是该编码的最后一条记录，如果不是，不能修改
        sql = "select * from ws_eng_assets_delivery_record " +
                " where assets_id = #{assets_id} order by id desc";
        paramsMap.put("assets_id",assets_id);
        paramsMap.put("sqlStr",sql);
        List<Map<String,Object>> list_id = publicMapper.getPublicItems(paramsMap);
        if(list_id.size()>0){
            newId = list_id.get(0).get("id").toString();
        }
        if(!newId.equals(map.get("id"))){
            return JsonResult.success(999); //表示不为最后出库记录，不能修改，返回999
        }

        //判断库存数量
        Integer stockin_total_num = null;
        sql = "select ifnull(sum(num),0) as total_num from ws_eng_assets_stockin_record where type_dtl_id=#{assets_id}";
        paramsMap.put("sqlStr",sql);
        List<Map<String,Object>> list_total_num = publicMapper.getPublicItems(paramsMap);
        if(list_total_num.size()>0){
            stockin_total_num = Integer.parseInt(list_total_num.get(0).get("total_num").toString());
        }
        Integer delivery_num = Integer.parseInt(map.get("num").toString());
        Integer delivery_totalNum = null;
        String id = map.get("id").toString();

        sql = "select ifnull(sum(delivery_num),0) as total_num from ws_eng_assets_delivery_record " +
                "where assets_id=#{assets_id} and id<>#{id}";
        paramsMap.put("sqlStr",sql);
        paramsMap.put("assets_id", assets_id);
        paramsMap.put("id", id);
        List<Map<String,Object>> delivery_total_num = publicMapper.getPublicItems(paramsMap);
        if(list_total_num.size()>0){
            delivery_totalNum = delivery_num + Integer.parseInt(delivery_total_num.get(0).get("total_num").toString());
        }

        Integer stockin_num = stockin_total_num - delivery_totalNum;
        if(stockin_num<0){
            //库存数量不足
            return JsonResult.success(0);
        }else {

            Integer quantity_ret = null;
            try {
                if (map.get("quantity_ret")!=null && !map.get("quantity_ret").toString().equals(""))
                {quantity_ret = Integer.parseInt(map.get("quantity_ret").toString());}
            }catch (Exception ex)
            {return JsonResult.success(400,"参数错误");}

            if (erpIsExist(map.get("erp").toString()))
            {
                sql = "UPDATE ws_eng_assets_Delivery_record" +
                        " SET" +
                        " assets_id=#{assets_id}, stockin_num=#{stockin_num}, delivery_num=#{delivery_num}, " +
                        "remarks=#{remarks}, delivery_man=#{delivery_man},erp=#{erp},purpose=#{purpose},quantity_ret=#{quantity_ret}, delivery_time=now()" +
                        " WHERE id=#{id} ";
                paramsMap.put("usqlStr", sql);
                paramsMap.put("assets_id", assets_id);
                paramsMap.put("id", map.get("id"));
                paramsMap.put("stockin_num", stockin_num);
                paramsMap.put("delivery_num", delivery_num);
                paramsMap.put("remarks", map.get("remarks"));
                paramsMap.put("purpose", map.get("purpose"));
                paramsMap.put("quantity_ret", quantity_ret);
                paramsMap.put("erp", map.get("erp"));
                paramsMap.put("delivery_man", map.get("delivery_man"));
                Integer updateNum = publicMapper.updateItems(paramsMap);
                return JsonResult.success(updateNum);
            }
            else
            {return JsonResult.success(400,"ERP单号不存在");}

        }
    }

    @Override
    public JsonResult<Integer> updateMtDeliveryRecordState(Map map) {
        Map paramsMap = new HashMap();
        String sql = "UPDATE ws_eng_assets_Delivery_record" +
                " SET" +
                " state=#{state}" +
                " WHERE id=#{id} ";
        paramsMap.put("usqlStr", sql);
        paramsMap.put("id", map.get("id"));
        paramsMap.put("state", map.get("state"));
        Integer updateNum = publicMapper.updateItems(paramsMap);
        return JsonResult.success(updateNum);
    }


    @Override
    public JsonResult<Integer> addMtDeliveryRecord(Map map) {
        Map paramsMap = new HashMap();
        String sql = "select type_dtl_id from ws_eng_assets_type_dtl where type_dtl_no = #{type_dtl_no}";
        paramsMap.put("type_dtl_no",map.get("typeDtlNo"));
        paramsMap.put("sqlStr",sql);
        String asset_id = "";
        Integer stockin_num = null;
        List<Map<String,Object>> list_type_dtl_id = publicMapper.getPublicItems(paramsMap);
        if(list_type_dtl_id.size()>0){
            asset_id = list_type_dtl_id.get(0).get("type_dtl_id").toString();
        }
        Integer stockin_total_num = null;
        paramsMap.put("type_dtl_id", asset_id);
        sql = "select ifnull(sum(num),0) as total_num from ws_eng_assets_stockin_record where type_dtl_id=#{type_dtl_id}";
        paramsMap.put("sqlStr",sql);
        List<Map<String,Object>> list_total_num = publicMapper.getPublicItems(paramsMap);
        if(list_total_num.size()>0){
            stockin_total_num = Integer.parseInt(list_total_num.get(0).get("total_num").toString());
        }
        Integer delivery_num = Integer.parseInt(map.get("num").toString());

        sql = "select ifnull(sum(delivery_num),0) as total_num from ws_eng_assets_delivery_record where assets_id=#{type_dtl_id}";
        paramsMap.put("sqlStr",sql);
        //paramsMap.put("assets_id", asset_id);
        List<Map<String,Object>> delivery_total_num = publicMapper.getPublicItems(paramsMap);
        if(list_total_num.size()>0){
            delivery_num = delivery_num + Integer.parseInt(delivery_total_num.get(0).get("total_num").toString());
        }

        stockin_num = stockin_total_num - delivery_num;
        if(stockin_num<0){
            //库存数量不足
            return JsonResult.success(0);
        }else {

            Integer quantity_ret = null;
            try {
                if (map.get("quantity_ret")!=null && !map.get("quantity_ret").toString().equals(""))
                {quantity_ret = Integer.parseInt(map.get("quantity_ret").toString());}
            }catch (Exception ex)
            {return JsonResult.success(400,"参数错误");}


            if (erpIsExist(map.get("erp").toString()))
            {sql = "INSERT INTO ws_eng_assets_Delivery_record" +
                    " VALUES" +
                    " (NULL, #{type_dtl_id}, #{stockin_num}, #{delivery_num}, #{erp},#{purpose},#{quantity_ret},#{remarks}," +
                    " #{delivery_man}, now(),0)";
                paramsMap.put("isqlStr", sql);
                paramsMap.put("stockin_num", stockin_num);
                paramsMap.put("delivery_num", map.get("num"));
                paramsMap.put("remarks", map.get("remarks"));
                paramsMap.put("purpose", map.get("purpose"));
                paramsMap.put("erp", map.get("erp"));
                paramsMap.put("quantity_ret", quantity_ret);
                paramsMap.put("delivery_man", map.get("delivery_man"));

                return JsonResult.success(publicMapper.saveItems(paramsMap));}
            else
            {
                return JsonResult.success(400,"ERP单号不存在");
            }

        }
    }

    @Override
    public JsonResult<Integer> deleMtDeliveryRecord(Integer id) {
        //----------这一步验证是否被锁定-----------//
        Map paramsMap = new HashMap();
        paramsMap.put("id",id);
        List<Map<String,Object>> list = getDeliveryList(paramsMap);
        if (list.size()>0)
        {
            if(!list.get(0).get("state").toString().equals("0"))
            { return JsonResult.error(408,"删除失败可能是记录已锁定"); }
        }
        else
        {return JsonResult.error(400,"删除失败，未找到对应记录"); }
        //----------这一步验证是否被锁定-----------//

        String sql = "DELETE FROM ws_eng_assets_delivery_record" +
                " WHERE" +
                " ID=#{id}";
        paramsMap.put("dsqlStr",sql);

        Integer updateNum = publicMapper.delItems(paramsMap);
        return JsonResult.success(updateNum);
    }

    @Override
    public void exportDelivetyData(HttpServletResponse response, Map map) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = null;
        try {
            fileName = URLEncoder.encode("物料出库详情表", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
        List<ExcelHeader> headerList = new ArrayList<>();
        headerList.add(new ExcelHeader("id", "id"));
        headerList.add(new ExcelHeader("type_main_name", "类型"));
        headerList.add(new ExcelHeader("mt_name", "物料名称"));
        headerList.add(new ExcelHeader("mt_code", "物料编码"));
        headerList.add(new ExcelHeader("k3_code", "K3编码"));
        headerList.add(new ExcelHeader("model", "型号"));
        headerList.add(new ExcelHeader("sizes", "规格参数"));
        headerList.add(new ExcelHeader("stockin_num", "库存数量"));
        headerList.add(new ExcelHeader("delivery_num", "出库数量"));
        headerList.add(new ExcelHeader("unit", "单位"));
        headerList.add(new ExcelHeader("erp", "关联ERP"));
        headerList.add(new ExcelHeader("conDept", "事业部"));
        headerList.add(new ExcelHeader("conProductNum", "机型"));
        headerList.add(new ExcelHeader("purpose", "借出用途"));
        headerList.add(new ExcelHeader("quantity_ret", "退回数量"));
        headerList.add(new ExcelHeader("remarks", "备注"));
        headerList.add(new ExcelHeader("delivery_man", "出库人"));
        ExcelHeader dateBackHeader = new ExcelHeader("delivery_time", "出库时间");
        dateBackHeader.setDataType(ExcelHeader.DATE);
        dateBackHeader.setFormat("yyyy-MM-dd HH:mm:ss");
        headerList.add(dateBackHeader);

        List<Map<String, Object>> dataList = getDeliveryList(map);
        OutputStream excelOutputStream = EasyExcelUtils.exportDataToExcel(headerList, dataList);
        try {
            response.getOutputStream().write(((ByteArrayOutputStream) excelOutputStream).toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Boolean erpIsExist(String erp) {
        if (erp.equals(""))
        {return true;}
        else
        {
            Map paramsMap = new HashMap();
            String sql = "SELECT * FROM uws_produceorder_confirmation_query WHERE conErpNo=#{conErpNo}";
            paramsMap.put("conErpNo",erp);
            paramsMap.put("sqlStr",sql);
            List<Map<String,Object>> list = publicMapper.getPublicItems(paramsMap);
            return list.size()>0;
        }
    }


}
